package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.*;
import com.atguigu.result.Result;
import com.atguigu.service.*;
import com.atguigu.vo.HouseQueryVo;
import com.atguigu.vo.HouseVo;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * projectName: shf
 *
 * @author: cbc
 * time: 2022/6/13 16:47 周一
 * description:
 */

@RequestMapping("/house")
@Controller
public class HouseController extends BaseController {
    @Reference
    private HouseService houseService;

    @Reference
    private CommunityService communityService;

    @Reference
    private HouseBrokerService houseBrokerService;

    @Reference
    private HouseImageService houseImageService;

    @Reference
    private UserFollowService userFollowService;

    @RequestMapping("/list/{pageNum}/{pageSize}")
    @ResponseBody
    public Result findListPage(
            @RequestBody HouseQueryVo houseQueryVo,
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize) {
        PageInfo<HouseVo> pageInfo = houseService.findListPage(pageNum, pageSize, houseQueryVo);
        return Result.ok(pageInfo);
    }

    //查看房源详情
    @RequestMapping("/info/{houseId}")
    @ResponseBody
    public Result info(@PathVariable("houseId") Long houseId, HttpServletRequest request) {
        //调用HouseService中根据id查询房源的方法
        House house = houseService.getById(houseId);
        //根据房源中小区的id获取所在的小区
        Community community = communityService.getById(house.getCommunityId());
        //获取该房源的经纪人
        List<HouseBroker> houseBrokers = houseBrokerService.findListByHouseId(houseId);
        //获取房源图片
        List<HouseImage> houseImages = houseImageService.findList(houseId, 1);

        //创建一个Map
        Map map = new HashMap<>();
        map.put("house", house);
        map.put("community", community);
        map.put("houseBrokerList", houseBrokers);
        map.put("houseImage1List", houseImages);

        //查询关注表
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("USER");

        Boolean isFollow = false;
        if (null != userInfo) {
            //证明已经登录，获取用户的id
            Long userId = userInfo.getId();
            //查询该用户是否已经关注该房源
            isFollow = userFollowService.isFollowed(userId, houseId);
        }

        //是否关注了该房源
        map.put("isFollow", isFollow);
        return Result.ok(map);
    }

}
